package edu.xhu.im.server;

import edu.xhu.model.common.constants.kafka.topic.ChatTopic;
import edu.xhu.model.im.constant.IMRedisKey;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

@Slf4j
@Component
@AllArgsConstructor
@EnableKafka
public class IMServerGroup implements CommandLineRunner {

    public static volatile long serverId = 0;

    private final StringRedisTemplate redisTemplate;

    private final List<IMServer> imServers;


    /***
     * 判断服务器是否就绪
     *
     * @return
     **/
    public boolean isReady() {
        for (IMServer imServer : imServers) {
            if (!imServer.isReady()) {
                return false;
            }
        }
        return true;
    }

    //每run一次,id+1,代表该节点的唯一标识
    @Override
    public void run(String... args) throws Exception {
        // 初始化SERVER_ID
        String key = IMRedisKey.IM_MAX_SERVER_ID;
        Long increment = redisTemplate.opsForValue().increment(key, 1);
        if (increment != null) {
            serverId = increment;
        }
        // 启动服务
        for (IMServer imServer : imServers) {
            imServer.start();
        }
        // 这是几号服务
        log.info("我是服务:{}", serverId);
        // 初始化topic
//        Properties props = new Properties();
//        props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "122.51.173.82:42770");
//        String topic = ChatTopic.BILL_CHAT_TOPIC.concat(String.valueOf(serverId));
//        try (AdminClient adminClient = AdminClient.create(props)) {
//            // 检查主题是否存在，如果不存在则创建
//            if (!adminClient.listTopics().names().get().contains(topic)) {
//                NewTopic newTopic = new NewTopic(topic, 1, (short) 1);
//                adminClient.createTopics(Collections.singleton(newTopic)).all().get();
//                log.info("Created Kafka topic: {}", topic);
//            }
//        } catch (Exception e) {
//            log.error("创建主题失败:{}", e.toString());
//            throw new RuntimeException();
//        }
    }

    @PreDestroy
    public void destroy() {
        // 停止服务
        for (IMServer imServer : imServers) {
            imServer.stop();
        }
    }
}
